import axios from 'axios'
import { addPendingRequest, removePendingRequest } from './apiThrottle'
import useUserStore from '@/stores/user'
import router from '@/router/index'

const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 20 * 1000,
  headers: {
    'content-Type': 'application/json'
  }
})

request.interceptors.request.use((config) => {
  const userStore = useUserStore()
  const token = userStore.token
  config.headers['x-access-token'] = token

  removePendingRequest(config)
  addPendingRequest(config)
  return config
})

request.interceptors.response.use(
  (response) => {
    removePendingRequest(response.config)

    const { code, data, message } = response.data
    if (code == '0000') {
      return data
    }
    // TODO 错误码处理
    ElMessage.error(message)

    return Promise.reject(new Error(message))
  },
  (error) => {
    console.dir(error)
    removePendingRequest(error.config || {})

    if (axios.isCancel(error)) {
      ElMessage.error('请勿重复发送请求' + error.message)
    } else {
      const { data, status } = error.response
      if (status === 401) {
        // 登录状态失效
        ElMessage.error(data.message)
        const userStore = useUserStore()
        userStore.logout()
        router.replace('/login')
      } else {
        ElMessage.error(error.message)
      }
    }
    return Promise.reject(new Error(error.message))
  }
)

export default request
